package tech.abing.spider.task.pageprocessor.sumuwang;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import tech.abing.spider.component.PageProcessor;
import tech.abing.spider.component.PageScript;
import tech.abing.spider.model.Proccessable;
import tech.abing.spider.page.OkPage;
import tech.abing.spider.page.Page;
import tech.abing.spider.request.BasicRequest;
import tech.abing.spider.request.PageRequest;
import tech.abing.spider.request.StartContext;
import tech.abing.spider.task.model.sumuwang.FundDataEntity;
import tech.abing.spider.task.model.sumuwang.FundNavEntity;
import tech.abing.spider.util.DateUtils;
import tech.abing.spider.util.StringUtils;

public class FundNavProcessor implements PageProcessor {

	
	private static Logger logger = Logger.getLogger(FundNavProcessor.class);
	
	static Pattern normalContain = Pattern.compile("pager");//正常页面必定会存在的字符，你也可以使用页面上其他的字符
	
	@Override
	public PageScript getJavaScript() {
		return null;
	}

	@Override
	public Pattern getNormalContain() {
		return normalContain;
	}

	@Override
	public void process(OkPage page, StartContext context, List<BasicRequest> queue,
			List<Proccessable> objectContainer) throws Exception {
		JSONObject jsonObj = JSONObject.fromObject(page.getContent());
		
		JSONObject pager = jsonObj.getJSONObject("pager");
		int pagecount = pager.getInt("pagecount");
		String pageStr = pager.getString("page");
		if(pagecount > 0){
			
			if("1".equals(pageStr)){
				//先处理第一页返回的数据
				String fundId = handNavData(page, objectContainer, jsonObj);
				
				for(int i = 2; i <= pagecount; i++){
					
					String url = "http://dc.simuwang.com/Fund/getNavHis.html?id="+fundId+"&page="+i+"&json=1";
					PageRequest request = context.createPageRequest(url, FundNavProcessor.class);
					request.getExtParams().put("fundId", fundId);
					
					request.putHeader("Cookie", "guest_id=1481883047; regsms=1481882878000; smppw_tz_auth=1; had_quiz_281090=1481882928000; PHPSESSID=3veq5avmupr1nibejqhtfd5r04; rz_token_6658=f800ad08789d0b26cc438d2bc83049bb.1481941519; stat_sessid=jb5e5gcrajm6v1hr8bu3qhgmq5; http_tK_cache=175d9e275bba231e2a097279543e4d4fbe1cfd51; cur_ck_time=1481941520; ck_request_key=IwEY6lyDRRH%2BCOaU1DvRVfvoEkMIdxJEUz45ymAuhG4%3D; passport=281090%09u_476668644256%09VlVQClFTB18BUVAFVVAFVw1WAQcDVQJUBwYBAgUFBVY%3D1b38ea2618; rz_u_p=d41d8cd98f00b204e9800998ecf8427e%3Du_476668644256; rz_rem_u_p=ip7zS1Cvi24LS6tsm%2F%2BasobNd9Bwrq0y5DuZAJclD9A%3D%24zxIAAybf1yufdhQt6M1IKEUQhYg0VrGymP%2BaSvbTukM%3D; passportmall=A1pXBAVRaBNmAQNSUAFZVVFXVAYP7378cf9565; autologin_status=1; fyr_ssid_n5776=fyr_n5776_iwslpudx; Hm_lvt_c3f6328a1a952e922e996c667234cdae=1481882878,1481941519; Hm_lpvt_c3f6328a1a952e922e996c667234cdae=1481941674");
					request.putHeader("Content-Type", "application/json; charset=UTF-8");
					request.putHeader(
							"User-Agent",
							"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36");
					request.putHeader("Accept", "application/json, text/javascript, */*; q=0.01");
					request.putHeader("Accept-Language", "zh-CN,zh;q=0.8");
					request.putHeader("Cache-Control", "no-cache");
					
					request.putHeader("Referer", "http://dc.simuwang.com/product/"+fundId+".html");
					
					request.putHeader("X-Requested-With", "XMLHttpRequest");
					request.putHeader("Host", "dc.simuwang.com");
					
					queue.add(request);
					
				}
			}else{
				//只处理数据
				handNavData(page, objectContainer, jsonObj);
			}
		}else{
			logger.info("请求:"+page.getRequest().getUrl()+",未检索到数据!");
		}
	}

	private String handNavData(OkPage page, List<Proccessable> objectContainer, JSONObject jsonObj)
			throws ParseException {
		JSONArray jsonArr = jsonObj.getJSONArray("data");
		
		Date curYearDate = DateUtils.parseDate(DateUtils.getYear() + "-01-01", new String[]{"yyyy-MM-dd"});
		
		String fundId = (String)page.getRequest().getExtParams().get("fundId");
		
		for(int i = 0; i < jsonArr.size(); i++){
			
			JSONObject json = jsonArr.getJSONObject(i);
			Date priceDate = DateUtils.parseDate(json.getString("price_date"), new String[]{"yyyy-MM-dd"});
			if(priceDate.compareTo(curYearDate) < 0){
				break;
			}
			
			FundNavEntity fundNav = new FundNavEntity();
			fundNav.setCumulativeNav(json.getDouble("cumulative_nav"));
			fundNav.setCumulativeNavWithdrawal(json.getDouble("cumulative_nav_withdrawal"));
			fundNav.setId(json.getString("id"));
			fundNav.setInitUnitValue(json.getDouble("init_unit_value"));
			fundNav.setNav(json.getDouble("nav"));
			
			if(json.get("price_change") != null && !"null".equals(json.get("price_change").toString())){
				fundNav.setPriceChange(json.getDouble("price_change"));
			}
			
			fundNav.setPriceDate(priceDate);
			fundNav.setFundId(fundId);
			StringUtils.removeSpace(fundNav);
			objectContainer.add(fundNav);
			
		}
		return fundId;
	}

	@Override
	public void processErrorPage(Page page, StartContext context,List<Proccessable> objectContainer) throws Exception {

	}

}
